package cn.topkinson.lagou.s3m4.user.service;

import cn.topkinson.base.api.code.CodeRemoteClient;
import cn.topkinson.lagou.s3m4.user.dao.UserMapper;
import cn.topkinson.lagou.s3m4.user.entity.UserPo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author huangzihao
 * @Date 2020/9/9 20:15
 */
@Service
public class UserService {

    @Reference
    private CodeRemoteClient codeRemoteClient;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final static String USER_TOKEN_KEY = "user:token:";

    public Boolean  register(String email, String password, String code) {
        if (0==codeRemoteClient.validate(email, code)){
            //插入数据
            Boolean result = userMapper.insert(email, password)>0;
            if (result){
                response.addCookie(new Cookie("token",getToken(email)));
            }
            return result;
        }else{
            return false;
        }
    }

    public Boolean isRegistered(String email) {
        return userMapper.selectByEmail(email)!=null;
    }

    public String login(String email, String password) {
        UserPo userPo = userMapper.selectByEmail(email);
        if (userPo!=null){
            if(userPo.getPassword().equalsIgnoreCase(password)){
                response.addCookie(new Cookie("token",getToken(email)));
                return getToken(email);
            }
        }
        return null;
    }

    private String getToken(String email){
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(USER_TOKEN_KEY+token, email,120, TimeUnit.MINUTES);
        return token;
    }

    public String info(String token) {
        return redisTemplate.opsForValue().get(USER_TOKEN_KEY+token);
    }
}
